/*
 * Copyright (c) Jack魏 2023 - 2023, All Rights Reserved.
 */

package cn.jackwei.yiyi.controller.view;

import cn.dev33.satoken.stp.StpUtil;
import cn.jackwei.yiyi.exception.BusinessException;
import cn.jackwei.yiyi.pojo.bean.SysUser;
import cn.jackwei.yiyi.service.sys.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 公共页面
 *
 * @author Jack魏
 * @since 2023/10/22 11:58
 */
@Controller
@RequestMapping("/")
public class IndexView {
    @Autowired
    private SysLoginService sysLoginService;

    @Value("${server.servlet.context-path}")
    public String rootPath;

    /**
     * 主页
     */
    @GetMapping("")
    public String index(Model model) {
        try {
            SysUser user = null;
            // 去数据库查询
            if (StpUtil.isLogin()) {
                // 获取当前登录用户id
                final String loginId = StpUtil.getLoginIdAsString();
                // 根据id获取session用户信息
                user = (SysUser) StpUtil.getSession().get(loginId);
            } else {
                user = sysLoginService.getUserByToken(StpUtil.getTokenValue());
                if (user == null) {
                    throw new BusinessException("token过期！");
                }
            }
            model.addAttribute("currentUser", user);
            // 项目根目录，用于前端固定请求接口
            model.addAttribute("rootPath", rootPath);
        } catch (Exception exception) {
            return "login";
        }
        return "index";
    }

    /**
     * 登录页面
     */
    @GetMapping("login")
    public String login() {
        return "login";
    }

    /**
     * 注册页面
     */
    @GetMapping("register")
    public String register() {
        return "register";
    }

    /**
     * 用户协议页面
     */
    @GetMapping("agreement")
    public String agreement() {
        return "agreement";
    }

    /**
     * 忘记密码
     */
    @GetMapping("forget")
    public String forget() {
        return "forget";
    }

    /**
     * 主页首先展示页面
     */
    @GetMapping("home")
    public String home() {
        return "index/home";
    }

    /**
     * 上传文件
     */
    @GetMapping("upload")
    public String upload() {
        return "index/upload";
    }
}
